// pages/my/my-add-address/index.js
var address = require("../../../utils/mock.js");
 
var app = getApp()
Page({
  /**
    * 控件当前显示的数据
    * provinces:所有省份
    * citys 选择省对应的所有市,
    * areas 选择市对应的所有区
    * consigneeRegion：点击确定时选择的省市县结果
    * animationAddressMenu：动画
    * addressMenuIsShow：是否可见
    */
  /**
   * 页面的初始数据
   */
  data: {
    animationAddressMenu: {},
    addressMenuIsShow: false,
    value: [0, 0, 0],
    provinces: [],
    citys: [],
    areas: [],
    consigneeName: "", //收货人
    phone: "",//手机号
    consigneeRegion: "",//所在省份 - 城市 - 区/县
    Current_university:"",//所在大学
    universityCampus:"",//所在校区
    detailedAddress: "",
    labelList: ["家", "公司", "学校"],            //标签
    globalUrl:"",//全局URL
    addressInfo:{
      recipientName:"",//收货人姓名
      phoneNumber:"",//收货人手机号
      province:"",//省份
      city:"",//城市
      district:"",//区/县
      university:"",//所在大学
      campus:"",//校区
      detailAddress:"",//详细地址
    },
  },
  consigneeNameInput: function(e) {
    
    this.setData({
      consigneeName: e.detail.value
    })
  },
  phoneInput: function(e) {
    
    this.setData({
      phone: e.detail.value
    })
  },
  consigneeRegionInput: function (e) {
    this.setData({
      consigneeRegion: e.detail.value
    })
  },
  Current_universityInput: function (e) {
    this.setData({
      Current_university: e.detail.value
    })
  },
  universityCampusInput: function (e) {
    this.setData({
      universityCampus: e.detail.value
    })
  },
  detailedAddressInput: function (e) {
    this.setData({
      detailedAddress: e.detail.value
    })
  },
  chooseLabelSelect: function(e) {
    var index = e.currentTarget.dataset.index;
    this.setData({
      labelDefault: index
    })
  },
  submit: function() {
    var consigneeName = this.data.consigneeName;
    console.log(consigneeName)
    var phone = this.data.phone;
    console.log(phone)
    var consigneeRegion = this.data.consigneeRegion;
    console.log(consigneeRegion)
    var Current_university = this.data.Current_university;
    console.log(Current_university)
    var universityCampus = this.data.universityCampus;
    console.log(universityCampus)
    var detailedAddress = this.data.detailedAddress
    console.log(detailedAddress)
    if (consigneeName == "") {
      wx: wx.showToast({
        title: '请输入姓名',
        icon: 'none'
      })
      return false
    }
    else if (phone == "") {
      wx: wx.showToast({
        title: '请输入手机号码',
        icon: 'none'
      })
      return false
    }
    else if (consigneeRegion == "") {
      wx: wx.showToast({
        title: '请选择所在地区',
        icon: 'none'
      })
      return false
    }
    else if (Current_university == "") {
      wx: wx.showToast({
        title: '请选择所在大学',
        icon: 'none'
      })
      return false
    }
    else if (universityCampus == "") {
      wx: wx.showToast({
        title: '请选择所在大学的校区',
        icon: 'none'
      })
      return false
    }
    else if (detailedAddress == "") {
      wx: wx.showToast({
        title: '请输入详细地址',
        icon: 'none'
      })
      return false
    }
    else {
      //处理输入后，点击保存的逻辑
      //获取用户的token
      const userInfo = wx.getStorageSync('UserData');
      // 获取小程序实例
      const app = getApp();
      // 获取全局变量
      const globalUrl = app.globalData.globalUrl;
      const islogin = app.globalData.islogin;
      console.log(globalUrl)
      this.setData({
        globalUrl:globalUrl,
        'addressInfo.recipientName':consigneeName,
        'addressInfo.phoneNumber':phone,
        'addressInfo.province':consigneeRegion,
        'addressInfo.city':consigneeRegion,
        'addressInfo.district':consigneeRegion,
        'addressInfo.university':Current_university,
        'addressInfo.campus':universityCampus,
        'addressInfo.detailAddress':detailedAddress,
      })
      // 将 addressInfo 对象转换为 JSON 字符串
      const addressJson = JSON.stringify(this.data.addressInfo);
      console.log(addressJson)
      //根据token获取请求
      wx.request({
        url: globalUrl+'/user/address/updateAddressById',
        method: 'POST',
        header: {
          "token": userInfo.token,
        },
        data: addressJson,
        success: (response) => {
          //来到此处，说明请求发送成功
          if(response.data.code === 200){ //成功添加地址列表到数据库
            console.log("地址数据");
            console.log(response.data.data)
            wx.navigateBack({
              data:1
            })
            wx.showToast({
              title: '修改成功',
              icon: 'none'
            })
            //把获取到的用户ID存入到域中，然后传递到地址管理界面
            //wx.setStorageSync('useraddress', response.data.data);
          }else{
            wx.showToast({
              title: '当前网络繁忙，稍后再试！',
              icon: 'none'
            })
          }
        },
      });
    }
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    // 默认联动显示北京
    var id = address.provinces[0].id
    this.setData({
      provinces: address.provinces,
      citys: address.citys[id],
      areas: address.areas[address.citys[id][0].id],
    })
  },
  // 点击所在地区弹出选择框
  select: function (e) {
    // 如果已经显示，不在执行显示动画
    if (this.data.addressMenuIsShow) {
      return false
    } else {
      // 执行显示动画
      this.startAddressAnimation(true)
    }
  },
  // 执行动画
  startAddressAnimation: function (isShow) {
    if (isShow) {
      // vh是用来表示尺寸的单位，高度全屏是100vh
      this.animation.translateY(0 + 'vh').step()
    } else {
      this.animation.translateY(40 + 'vh').step()
    }
    this.setData({
      animationAddressMenu: this.animation.export(),
      addressMenuIsShow: isShow,
    })
  },
  // 点击地区选择取消按钮
  cityCancel: function (e) {
    this.startAddressAnimation(false)
  },
  // 点击地区选择确定按钮
  citySure: function (e) {
    var that = this
    var city = that.data.city
    var value = that.data.value
    this.startAddressAnimation(false)
    // 将选择的城市信息显示到输入框
    var consigneeRegion = that.data.provinces[value[0]].name + '-' + that.data.citys[value[1]].name + '-' + that.data.areas[value[2]].name
    that.setData({
      consigneeRegion: consigneeRegion,
    })
  },
  // 处理省市县联动逻辑
  cityChange: function (e) {
    var value = e.detail.value
    var provinces = this.data.provinces
    var citys = this.data.citys
    var areas = this.data.areas
    var provinceNum = value[0]
    var cityNum = value[1]
    var countyNum = value[2]
    // 如果省份选择项和之前不一样，表示滑动了省份，此时市默认是省的第一组数据，
    if (this.data.value[0] != provinceNum) {
      var id = provinces[provinceNum].id
      this.setData({
        value: [provinceNum, 0, 0],
        citys: address.citys[id],
        areas: address.areas[address.citys[id][0].id],
      })
    } else if (this.data.value[1] != cityNum) {
      // 滑动选择了第二项数据，即市，此时区显示省市对应的第一组数据
      var id = citys[cityNum].id
      this.setData({
        value: [provinceNum, cityNum, 0],
        areas: address.areas[citys[cityNum].id],
      })
    } else {
      // 滑动选择了区
      this.setData({
        value: [provinceNum, cityNum, countyNum]
      })
    }
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
 
  },
 
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var animation = wx.createAnimation({
      duration: 500,
      timingFunction: 'linear',
    })
    this.animation = animation


    //加载界面赋值
    const addressInfo = wx.getStorageSync('addressInfo')
    this.setData({
      addressInfo:addressInfo,
      consigneeName: addressInfo.recipientName,
      phone: addressInfo.phoneNumber,//手机号
      consigneeRegion: addressInfo.province+"-"+addressInfo.city+"-"+addressInfo.district,//所在省份 - 城市 - 区/县
      Current_university:addressInfo.university,//所在大学
      universityCampus:addressInfo.campus,//所在校区
      detailedAddress: addressInfo.detailAddress,
  
    })
    console.log("获取到的地址信息为：",addressInfo)

  },
 
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
 
  },
 
  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
 
  },
 
  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
 
  },
 
  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
 
  },
 
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
 
  }
})